package com.xci.wx.mp.controller;

import com.xci.core.base.SMap;
import com.xci.core.base.WebController;
import com.xci.core.helper.JsonHelper;
import com.xci.core.helper.WebHelper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("/wx/message")
public class MessageController extends WebController {
    @Resource
    private WxMpService wxMpService;

    @ResponseBody
    @GetMapping(value = "/send")
    public Object send() throws WxErrorException {

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("ojj7SwstGPMw5qOONGUBpmRRK1NI")
                .templateId("sdhhtst-sHVuYkGbIMeVlOY-rUcos5LN-krtEgO0mpw")
                .url("http://www.xa96716.com/wx/message/details")
                .build();

        templateMessage.addData(new WxMpTemplateData("first", "您好，您在管理处办理的业务以及完成。"));
        templateMessage.addData(new WxMpTemplateData("keyword1", "维修企业备案申请"));
        templateMessage.addData(new WxMpTemplateData("keyword2", "备案成功","#de2268"));
        templateMessage.addData(new WxMpTemplateData("keyword3", "2019-12-12"));
        templateMessage.addData(new WxMpTemplateData("remark", "请保持您的手机号通畅，成功后会有消息提醒到您的手机。"));

        return wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    @ResponseBody
    @GetMapping(value = "/details", produces = "text/plain;charset=utf-8")
    public Object details() {
        return "模板消息测试页面";
    }

    @ResponseBody
    @GetMapping(value = "/users")
    public Object users() throws WxErrorException {
        return wxMpService.getUserService().userList(null);
    }

    @GetMapping(value = "/page")
    public String page(ModelMap map) throws WxErrorException {
        var url = WebHelper.getSiteFullUrl(getRequest().getRequestURI());
        var sign = wxMpService.createJsapiSignature(url);
        map.put("sign", sign);
        return "wechat";
    }
}
